//
//  UrlRequestManager.m
//  LO_MUSIC
//
//  Created by 胡林 on 16/2/29.
//  Copyright © 2016年 杨少锋. All rights reserved.
//

#import "UrlRequestManager.h"

@implementation UrlRequestManager

+(void)requestWith:(requestUrlType)Type URL:(NSString *)URL condition:(NSDictionary *)condition SuccessBlock:(successBlock)successBlock faileBlock:(faileBlock)faileBloc{
    if (Type == GET) {
        UrlRequestManager * manager = [[UrlRequestManager alloc] init];
        [manager get:URL condition:condition success:successBlock faile:faileBloc];
    }else{
        UrlRequestManager * manager = [[UrlRequestManager alloc] init];
        [manager post:URL condition:condition success:successBlock faile:faileBloc];
        
    }
}
//GET
//@param url url
//@param dic 参数


-(void)get:(NSString *)url condition:(NSDictionary *)condition success:(successBlock)success faile:(faileBlock)faile{
    NSURLSession * session = [NSURLSession sharedSession];
    // 把字符串用UTF8编码（主要防止字符串里有汉字）
//拼接url
    __block NSMutableString * urlStr = [NSMutableString stringWithString:url];
    [urlStr appendString:@"?"];
    
    [condition enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        [urlStr appendString:[NSString stringWithFormat:@"%@=%@&",key,obj]];
    }];
    [urlStr substringToIndex:[url length]-2];
    //转码
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:urlStr];
    NSString * urlString = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:set];
    
    //设置request
       NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];/*拼接并转码之后的*/
    //设置请求方式
    [request setHTTPMethod:@"GET"];
       //请求头：
    NSURLSessionTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data && !error) {

        id item = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            if (success) {
                //如果解析成功
                success(item);
                
            }else{
                if (faile) {
                    faile(error);
                }
            }
        }
    }];
    //开启
    [task resume];
}

//POST
-(void)post:(NSString *)url condition:(NSDictionary *)condition success:(successBlock)success faile:(faileBlock)faile{
    NSURLSession *session = [NSURLSession sharedSession];
    // 拼接url
    NSMutableString *urlStr = [NSMutableString stringWithString:url];
    // 拼接?
    [urlStr appendString:@"?"];
    
    // 转码
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:urlStr];
    NSString * urlString = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:set];
    
    // body
    __block NSMutableString *bodyStr = [NSMutableString string];
    [condition enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        [bodyStr appendString:[NSString stringWithFormat:@"%@=%@&",key,obj]];
    }];
    [bodyStr substringToIndex:[bodyStr length]-2];
    
    // 设置request
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    // 设置请求方式
    [request setHTTPMethod:@"POST"];
    // 设置body
    NSData *date = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:date];
    
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //NSLog(@"data = %@, err = %@",data,error);
        if (data && !error) {
            id item = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
            if (success) {  //如果解析成功
                success(item);
                return ;
            }else {
                NSLog(@"successblock 为空");
                return;
            }
        }
        //
        if (faile) {
            faile(error);
        }
    }];
    [task resume];
}
//static修饰的不会被释放
single_implementation(UrlRequestManager);


@end
